function  rdPLimit(concurrency) {
  /**
   * target：对并行的promise进行并发数量的限制
   * 
   * const limit = pLimit(2);
   * const input = [
   *    limit(() => fetchSomething('foo')),
   *    limit(() => fetchSomething('bar')),
   *    limit(() => doSomething())
   * ];
   * const result = await Promise.all(input);
   * 
   */
  let active = 0;
  let queue = [];

  const resumeQueue = async (key) => {
    console.log(key, '当前进行任务数量：', active);
    if (active < concurrency && queue.length) {
      active++;
      await queue.shift()();
      active--;
      resumeQueue('后续唤起');
    }
  }


  const promiseGenerator = (cb) => {
    return new Promise(resolve => {
      const core = async () => {
        const result = await cb();
        resolve(result);
      }
      queue.push(core)
      /**
       * 优化构想：
       * 使初始化时的resumeQueue变为微任务
       * 但目前存在bug，FIXME
       */
      // (async () => {
      //   await new Promise.resolve();
      //   resumeQueue('初始化');
      // })();
      resumeQueue('初始化');
    })
  }
  return promiseGenerator;
}

module.exports = rdPLimit;